package com.lxl.securitypermission.config.exception;

import com.lxl.securitypermission.constant.HttpCode;
import com.lxl.securitypermission.dto.ResponseResult;
import java.util.Arrays;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 绫小路
 * @date 2021/1/3 19:25
 * @description 全局异常
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

  Logger logger = LoggerFactory.getLogger("ADVICE");

  /**
   * 断言异常处理
   */
  @ExceptionHandler(IllegalArgumentException.class)
  @ResponseBody
  public ResponseResult illegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
    logger.error("异常请求-{}?{},参数:[{}]远程地址-{} 异常信息-{}",
        request.getRequestURL(),
        request.getQueryString(),
        getParams(request),
        request.getRemoteAddr(),
        e.getMessage());
    return new ResponseResult(HttpCode.FAIL, e.getMessage());
  }

  @ExceptionHandler(RuntimeException.class)
  @ResponseBody
  public ResponseResult RuntimeException(RuntimeException e, HttpServletRequest request) {
    logger.error("异常请求-{}?{},参数:[{}]远程地址-{} 异常信息-{}",
        request.getRequestURL(),
        request.getQueryString(),
        getParams(request),
        request.getRemoteAddr(),
        e.getMessage());
    return new ResponseResult(HttpCode.FAIL, e.getMessage());
  }

  private StringBuffer getParams(HttpServletRequest request) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    StringBuffer params = new StringBuffer();
    for (Map.Entry<String, String[]> entity : parameterMap.entrySet()) {
      params.append(entity.getKey() + "=" + Arrays.toString(entity.getValue()) + ",");
    }
    return params;
  }
}
